
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>

void MainWindow::dataReceived_Client() {

    while (socket->canReadLine()) {
        QString str = socket->readLine();

        QString username = "unknown";
        QString msg;
        QString text;
        QString todosJugadoresCon;

        int pound = str.indexOf('#');
        if(pound >= 0){
            todosJugadoresCon = str.left(pound);
            GetPlayerGUI(todosJugadoresCon);
            str = str.mid(pound + 1);
        }

        // get username, text
        int colonPos = str.indexOf(':');
        if (colonPos >= 0) {
            username = str.left(colonPos);
            msg = str.mid(colonPos + 1);
        } else {
            msg = str;
        }
        int forMSM = msg.indexOf('|');
        if(forMSM >= 0){
            text = msg.mid(forMSM + 1);
            ChatConnection->insertHtml("<b>" + username + "</b>: " + text + "<br></br>");
        }else {

        command = (msg).toLocal8Bit().constData();

        if(jugador != username){
           MultiCommand(command);
        }
        }
    }
}

void MainWindow::serverDisconnected()
{
     ui->statusBar->showMessage("Disconnected.");
     JoinGame->setEnabled(true);
     ui->btnSend->setEnabled(false);

     socket->deleteLater();
}

void ConnectThread::run(){

    socket = new QTcpSocket();

    socket->connectToHost(hostname, 5000);
    if (!socket->waitForConnected())  {
        errorMsg = "Uh oh, Unable to connect to server.";
        return;
    }

    QString data = QString("*USER ") + username + "\n";
    qDebug() << "Sending " << data;
    socket->write(data.toStdString().c_str());

    // wait for response from server
    while (!socket->canReadLine() && socket->state() == QAbstractSocket::ConnectedState) {
        socket->waitForReadyRead();
    }

    if (socket->state() != QAbstractSocket::ConnectedState) {
        errorMsg = "Uh oh, Server disconnected.";
        socket->deleteLater();
        return;
    }

    data = socket->readLine().trimmed();

    if (data != "+OK") {
        errorMsg = "Uh oh, Username not valid.";
        socket->deleteLater();
        return;
    }

    data = QString("*PASS ") + password + "\n";
    qDebug() << "Sending " << data;
    socket->write(data.toStdString().c_str());

    // wait for response from server
    while (!socket->canReadLine() && socket->state() == QAbstractSocket::ConnectedState) {
        socket->waitForReadyRead();
    }

    if (socket->state() != QAbstractSocket::ConnectedState) {
        errorMsg = "Uh oh, Server disconnected.";
        socket->deleteLater();
        return;
    }

    data = socket->readLine().trimmed();
    if (data != "+OK") {
        errorMsg = "Uh oh, Password not valid.";
        socket->deleteLater();
        return;
    }
    success = true;

    socket->moveToThread(QApplication::instance()->thread());
}

void MainWindow::connectFinished(){

    if(thread->GetSuccess()){
        socket = thread->getSocket();

        connect(socket, SIGNAL(readyRead()), this, SLOT(dataReceived_Client()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
       JoinGame->setEnabled(false);
       ui->btnSend->setEnabled(true);

       GUIDone = false;
       MultiAction(jugador + ":| joined.");
    }else{
        QMessageBox::warning(this, "asdf",thread->GetErrorMSG());
    }

}


